package com.chungkui.check.configparser.impl;

import com.chungkui.check.configparser.ParsingUtil;
import com.chungkui.check.configparser.RulesParser;
import com.chungkui.check.configparser.bean.CheckConfig;
import com.chungkui.check.exception.RuleParseException;
import com.chungkui.check.util.JsonUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * @Author: jason
 * @Date: 2020/1/16 10:33
 * @Version 1.0
 */
public class RulesParserImpl implements RulesParser {
    private final Logger log = LoggerFactory.getLogger(RulesParserImpl.class);

    @Override
    public void parsing(CheckConfig checkConfig, String[] localValue, String localRules, Object remoteConfig) {
        if (remoteConfig != null) {
            /*remote配置*/
            List<Map<String, Object>> configs = (List<Map<String, Object>>) remoteConfig;
            parsing(checkConfig, configs);
        } else {
            /*本地配置*/
            parsingLocal(checkConfig, localValue, localRules);
        }
    }

    private void parsingLocal(CheckConfig checkConfig, String[] localRulesArr, String localRulesJson) {
        /*本地配置*/
        List<Map<String, Object>> configs = Lists.newArrayList();
        if (StringUtils.isNotEmpty(localRulesJson)) {
            List<Map<String, Object>> localList = JsonUtil.jsonToObject(localRulesJson, List.class);
            if (CollectionUtils.isNotEmpty(localList)) {
                configs.addAll(localList);
            }
        }
        if (localRulesArr != null) {
            for (int i = 0; i < localRulesArr.length; i++) {
                Map<String, Object> config = JsonUtil.json2map(localRulesArr[i]);
                if (config == null) {
                    log.error("json2map fail,json format is incorrect :{}", localRulesArr[i]);
                    throw new RuleParseException("json2map fail");
                } else {
                    configs.add(config);
                }

            }
        }
        parsing(checkConfig, configs);
    }

    /**
     * @param checkConfig
     * @param configs
     */
    private void parsing(CheckConfig checkConfig, List<Map<String, Object>> configs) {
        if (CollectionUtils.isNotEmpty(configs)) {
            checkConfig.setMatchExpressions(ParsingUtil.buildExpressions(configs));
        }
    }

}
